import React, { Component, Suspense, useEffect, useState } from "react";
import { Route, Routes, useLocation, useNavigate, useParams, useSearchParams } from "react-router-dom";
import routes from "./routes";
import { Mask, DotLoading } from "antd-mobile";
import store from '@/store'  
const styleMask = {
    position: 'absolute',
    top: '50%',
    left: '50%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: '150px',
    height: '150px',
    marginTop: '-75px',
    marginLeft: '-0',
    background: '',
    borderRadius: '',
    transform: 'translate(-50%, -50%)'
}


const isMastLogin = function (pathname) {
    const isMastLoginPath = ['store', 'detail', 'personal', 'update'];
    const loginReducer = store.getState().login.loginInfo
    return !loginReducer?.id && isMastLoginPath.some((e) => pathname.indexOf(e) > -1)
}

const Element = function Element(props) {
    // 函数组件可以直接获取props 和路由元信息  
    const { component: Component, meta = {}, path } = props;
    document.title = meta.title || 'reactv6 18';
    // 登陆劫持

    const location = useLocation(),
        navigate = useNavigate(),
        params = useParams(),
        [ups] = useSearchParams(),
        [isLogin, setLogin] = useState(false),
        { pathname, search } = useLocation()




    useEffect(() => {
        if (isMastLogin(pathname)) {
            setLogin(false)
            navigate(`/login?to=${pathname}&${ups.toString()}`, {
                replace: true
            })
        } else {
            setLogin(true)
        }
    })



    return isLogin ? <Component
        location={location}
        navigate={navigate}
        params={params}
        ups={ups}
    /> : <Mask
        visible={true}
        onMaskClick={() => setVisible(false)}
        opacity='thick'
    >
        <DotLoading color='primary' style={styleMask} />
    </Mask >
}

const setVisible = () => { return false }

export default function RouterView() {
    return <Suspense fallback={
        <Mask
            visible={true}
            onMaskClick={() => setVisible(false)}
            opacity='thick'
        />
    }>
        <Routes>
            {
                routes.map((e) => {
                    let { path, name, component, meta } = e
                    return <Route
                        path={path}
                        key={name}
                        element={
                            <Element
                                component={component}
                                meta={meta}
                                name={name}
                            />
                        }
                    ></Route>
                })
            }
        </Routes>
    </Suspense>
}